package main

import (
	"fmt"
	"image"
	"path/filepath"

	"demserver/src/elevation"
)

func main() {
	// Use the actual GeoTIFF file
	filename := "./demdata/ClipResult.tif"

	// Get absolute path to the file
	absPath, err := filepath.Abs(filename)
	if err != nil {
		fmt.Printf("Failed to get absolute path: %v\n", err)
		return
	}

	fmt.Printf("Loading GeoTIFF file: %s\n", absPath)
	geoTiff, err := elevation.LoadGeoTIFF(absPath)
	if err != nil {
		fmt.Printf("Failed to load GeoTIFF: %v\n", err)
		return
	}
	fmt.Println("GeoTIFF loaded successfully")
	fmt.Printf("Image dimensions: %dx%d\n", geoTiff.Width, geoTiff.Height)
	fmt.Printf("Image type: %T\n", geoTiff.Image)

	// Check if it's a Gray16 image
	if grayImg, ok := geoTiff.Image.(*image.Gray16); ok {
		fmt.Println("Image is Gray16 type")
		// Test a few pixel values directly
		testPixels := [][2]int{
			{1000, 1000},
			{5000, 5000},
			{10000, 10000},
		}

		for _, pixel := range testPixels {
			x, y := pixel[0], pixel[1]
			value := grayImg.Gray16At(x, y)
			fmt.Printf("Pixel (%d, %d): Gray16 value = %d\n", x, y, value.Y)
		}
	}

	// Test coordinate conversion with one of the provided coordinates
	lat := 31.02659757575758
	lon := 103.54607363636364
	expected := 780.2126995110525

	x, y, err := geoTiff.LatLonToPixel(lat, lon)
	if err != nil {
		fmt.Printf("Failed to convert coordinates (%f, %f): %v\n", lat, lon, err)
		return
	}

	fmt.Printf("\nCoordinate conversion test:\n")
	fmt.Printf("Lat: %f, Lon: %f\n", lat, lon)
	fmt.Printf("Pixel coordinates: X=%f, Y=%f\n", x, y)

	// Check if coordinates are within bounds
	if x < 0 || y < 0 || x >= float64(geoTiff.Width) || y >= float64(geoTiff.Height) {
		fmt.Printf("Coordinates out of bounds. Image size: %dx%d\n", geoTiff.Width, geoTiff.Height)
		return
	}

	// Get elevation value
	elevationVal, err := geoTiff.GetElevation(x, y)
	if err != nil {
		fmt.Printf("Failed to get elevation at (%f, %f): %v\n", x, y, err)
		return
	}

	fmt.Printf("Expected elevation: %f\n", expected)
	fmt.Printf("Actual elevation: %f\n", elevationVal)
	fmt.Printf("Difference: %f\n", elevationVal-expected)

	// Test individual pixel values around the point for more detailed analysis
	fmt.Printf("\nDetailed pixel analysis around (%f, %f):\n", x, y)
	xInt := int(x)
	yInt := int(y)

	for dy := -1; dy <= 1; dy++ {
		for dx := -1; dx <= 1; dx++ {
			px := xInt + dx
			py := yInt + dy

			// Check bounds
			if px >= 0 && py >= 0 && px < geoTiff.Width && py < geoTiff.Height {
				if grayImg, ok := geoTiff.Image.(*image.Gray16); ok {
					value := grayImg.Gray16At(px, py)
					fmt.Printf("Pixel (%d, %d): Gray16 value = %d\n", px, py, value.Y)
				}
			}
		}
	}
}
